﻿using PmSadis.Repositories.Abstract;
using PmSadis.Models;
using System.Linq;
using PmSadis.Dal;
using System;
using System.Data.Entity;

namespace PmSadis.Repositories
{
    /// <summary>
    /// Хранилище машинистов справочных работ
    /// </summary>
    public class WorkDriverRepository : IListRepository<WorkDriver>
    {
        private ModelsContext _context = new ModelsContext();

        /// <summary>
        /// Полный список материалов
        /// </summary>
        public IQueryable<WorkDriver> All
        {
            get
            {
                return _context.WorkDrivers;
            }
        }

        /// <summary>
        /// Удалить машиниста
        /// </summary>
        /// <param name="id">Идентификатор машиниста</param>
        public void Delete(object id)
        {
            var workDriverId = (int)id;
            var workDriver = _context.WorkDrivers.FirstOrDefault(x => x.WorkDriverId == workDriverId);
            if (workDriver == null) return;

            _context.WorkDrivers.Remove(workDriver);
            _context.SaveChanges();
        }

        /// <summary>
        /// Создать или редактировать машиниста
        /// </summary>
        /// <param name="workMaterial">Машинист</param>
        public object Edit(WorkDriver workDriver)
        {
            var dateNow = DateTime.Now;
            if (workDriver.WorkDriverId == 0)
            {
                workDriver.DateCreate = dateNow;
                workDriver.DateUpdate = dateNow;
                _context.Entry(workDriver).State = EntityState.Added;
            }
            else
            {
                workDriver.DateUpdate = dateNow;
                _context.Entry(workDriver).State = EntityState.Modified;
            }

            _context.SaveChanges();

            return workDriver.WorkDriverId;
        }
    }
}
